home *** CD-ROM | disk | FTP | other *** search
- Path: svnews.ubinet.ubs.com!ubszh!ubszh!jis
- From: jis@ubszh.net.ch (Johnston Ian (by ubsswop))
- Newsgroups: comp.lang.c++
- Subject: Re: Help with Bug Pleeeeease!
- Date: 29 Jan 1996 16:18:52 GMT
- Organization: UBS
- Distribution: world
- Message-ID: <4eis1c$hbm@ubszh.fh.zh.ubs.com>
- References: <tday-2801961838030001@tday.slip.netcom.com>
- NNTP-Posting-Host: nol2179.fh.zh.ubs.com
-
- In article <tday-2801961838030001@tday.slip.netcom.com>, tday@netcom.com (Tony Day) writes:
- |>
- |> I hope some C++ wizard out there can help me debug this apparantly simple
- |> program. I am teaching myself C++ with Prata╣s │C++ primer +▓ and am
- |> completely stuck with one of the problems at the end of CH11.
- |>
- |> The aim of the excercise is to overload the +operator for a String Class
- |> (which consists of a char * and int holding the string length). I have
- |> written 3 overloaded + operators, one adds a String to a String (this
- |> seems to work), the other two add a C string to a String.
- |>
- |> The problem is with the latter two. When the assignment operator (not
- |> written by me) is invoked after one of these + operators, the whole system
- |> crashes (I am using Symantec Think C++ 7.04 on a Mac quadra) even if the
- |> assignment operator invokes different Strings to the + operators. This is
- |> what happens when the main (below) is run. If the assignment call is
- |> before the +operator call, no problem.
-
- [...]
-
- |> String String::operator+(const String & st) const
- |> {
- |> String temp1;
- |> delete [] temp1.str;
- |> temp1.len = st.len+len;
- |> temp1.str = new char[temp1.len+1]; <<<<<<<<<<<<<<<<
- |> strcpy(temp1.str,str);
- |> for (int i=len; i< temp1.len; i++)
- |> temp1.str[i]=st.str[i-len];
- |> temp1.str[temp1.len+1]='\0'; <<<<<<<<<<<<<<<<
- |> cout << temp1.len << " length1st\n";
- |> return temp1;
- |> }
-
- Here's the problem. You are writing over memory you don't own. As you
- allocate (temp1.len + 1) bytes, the valid indexes are 0..temp1.len.
- You have probably trashed the internal heap management used by new (or
- malloc). Interestingly, this didn't crash on a Sun...
-
- Wouldn't this have been easier:
-
- strcpy(temp1.str, str);
- strcat(temp1.str, st.str);
-
- It may or may not be more efficient, but it is unlikely that strcat() has
- any bugs in it...
-
- I understand this is an exercise, but you could probably make these
- operations more efficient. Mail me if you are interested in further details.
-
- Ian
-
-
-